package main

import (
	"context"
	"log"
	"time"
	"todo-server/db"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
)

func main() {
	c := gin.Default()

	c.GET("/todo", func(c *gin.Context) {
		ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
		cur, err := db.MongoCollection("todo").Find(ctx, bson.D{})
		var mi []interface{}
		if err != nil {
			log.Fatalln(err)
		}
		for cur.Next(ctx) {
			var result struct {
				Title  string    `json:"title"`
				Status string    `json:"status"`
				Time   time.Time `json:"time"`
				ID     string    `json:"_id" bson:"_id"`
				Note   string    `json:"note"`
			}
			err := cur.Decode(&result)
			if err != nil {
				log.Fatal(err)
			}
			mi = append(mi, result)

		}
		if err := cur.Err(); err != nil {
			log.Fatal(err)
		}

		defer cancel()
		// 结束
		c.JSON(200, gin.H{
			"data": mi,
		})
	})
	// 添加Todo, 适合做冷数据的存储
	c.POST("/todo", func(c *gin.Context) {
		title := c.DefaultQuery("title", "")
		status := c.DefaultQuery("status", "1")
		note := c.DefaultQuery("note", "")
		ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
		defer cancel()
		result, err := db.MongoCollection("todo").InsertOne(ctx,
			bson.M{"title": title, "status": status, "time": time.Now(), "note": note},
		)
		if err != nil {
			log.Fatalln(err)
		}
		if result.InsertedID != nil {
			c.JSON(200, gin.H{
				"data": true,
			})
		}
	})
	c.PUT("/todo", func(c *gin.Context) {
		id := c.DefaultQuery("id", "")
		title := c.DefaultQuery("title", "")
		status := c.DefaultQuery("status", "")
		if title == "" || id == "" || status == "" {
			c.JSON(200, gin.H{
				"msg": "请传入正确的值",
			})
			c.Abort()
			return
		}
		r, err := db.MongoCollection("todo").UpdateByID(context.Background(), id, bson.M{
			title:  title,
			status: status,
		})
		if r.UpsertedID != nil {
			log.Fatalln(err)
		}
		c.JSON(200, gin.H{
			"data": true,
		})
	})
	log.Fatal(c.Run(":8080"))
	defer db.MongoClient.Disconnect(context.TODO())
}
